package cn.oracle.eshop.cart.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.oracle.eshop.cart.dao.ShoppingCartDAO;
import cn.oracle.eshop.cart.dao.ShoppingCartItemDAO;
import cn.oracle.eshop.cart.domain.ShoppingCartDO;
import cn.oracle.eshop.cart.domain.ShoppingCartItemDO;
import cn.oracle.eshop.cart.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**购物车管理模块service组件
 * @author wyh
 * @ClassName ShoppingCartServiceImpl
 * @date 2022/3/28 /21:34
 */
@Slf4j
@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {
   /**购物车管理模块的DAO组件*/
    @Autowired
    private ShoppingCartDAO shoppingCartDAO;
    /**购物车条目管理模块的DAO组件*/
    @Autowired
    private ShoppingCartItemDAO shoppingCartItemDAO;
    /***
     * 添加购物车商品条目
     * @author wyh
     * @date 2022/3/28
     * @param userAccountId 用户ID
     * @param goodsSkuId  商品ID
     * @return 处理结果
    */

    @Override
    public Boolean addShoppingCartItem(Long userAccountId, Long goodsSkuId) {
        //先查询一下用户的购物车
        ShoppingCartDO shoppingCartDo = shoppingCartDAO.getShoppingCartByUserAccountId(userAccountId);
        //如果购物车不存在，则新增一个购物车
        if(BeanUtil.isEmpty(shoppingCartDo)){
            shoppingCartDo=new ShoppingCartDO();
            shoppingCartDo.setUserAccountId(userAccountId);
            shoppingCartDo.setGmtCreate(new Date());
            shoppingCartDo.setGmtModified(new Date());
        }
        shoppingCartDAO.saveShoppingCart(shoppingCartDo);
        //查询一下购物车中是否存在这个商品sku对应的条目
        ShoppingCartItemDO shoppingCareItemDo = shoppingCartItemDAO.getShoppingCareItemByGoodsSkuId(shoppingCartDo.getId(), goodsSkuId);
        //如果没有这个商品条目，则新增一个商品条目
        if(BeanUtil.isEmpty(shoppingCareItemDo)){
            shoppingCareItemDo=new ShoppingCartItemDO();
            shoppingCareItemDo.setShoppingCartId(goodsSkuId);
            shoppingCareItemDo.setPurchaseQuantity(1L);
            shoppingCareItemDo.setGmtCreate(new Date());
            shoppingCareItemDo.setGmtModified(new Date());

            shoppingCartItemDAO.saveShoppingCartItem(shoppingCareItemDo);

        }
        //如果购物车中已经有这个商品条目了，则对已有的商品的购买数量累加1
        else {
            shoppingCareItemDo.setPurchaseQuantity(shoppingCareItemDo.getPurchaseQuantity()+1L);
            shoppingCareItemDo.setGmtCreate(new Date());
            shoppingCareItemDo.setGmtModified(new Date());
            shoppingCartItemDAO.updateShoppingCartItem(shoppingCareItemDo);
        }
        return false;
    }
}
